package com.example.alaporres;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.alaporres.FoursquareApp.FsqAuthListener;

public class LoginActivity extends Activity implements OnClickListener,
		LocationListener {

	EditText latitudeEt;
	EditText longitudeEt;

	private FoursquareApp mFsqApp;
	private ListView mListView;
	private NearbyAdapter mAdapter;
	private ArrayList<FsqVenue> mNearbyList;
	private ProgressDialog mProgress;

	public static final String CLIENT_ID = "OZBKL4OVYAQ3I5KSOIFTBVOECZD55FHVLD11HQZEFX0YZXIE";
	public static final String CLIENT_SECRET = "2AUWZGH5DQCSWWSL3IIZDMPM05GDN1LQKAGPY3RD452EDMWC";

	LocationManager lm;
	String towers;
	int lat = 0;
	int longitu = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.login);

		latitudeEt = (EditText) findViewById(R.id.et_latitude);
		longitudeEt = (EditText) findViewById(R.id.et_longitude);
		final TextView nameTv = (TextView) findViewById(R.id.tv_name);
		Button connectBtn = (Button) findViewById(R.id.b_connect);
		Button goBtn = (Button) findViewById(R.id.b_go);
		mListView = (ListView) findViewById(R.id.lv_places);

		mFsqApp = new FoursquareApp(this, CLIENT_ID, CLIENT_SECRET);

		mAdapter = new NearbyAdapter(this);
		mNearbyList = new ArrayList<FsqVenue>();
		mProgress = new ProgressDialog(this);

		// placing a pin at your current location and zooming there
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria crit = new Criteria();

		towers = lm.getBestProvider(crit, false);

		Location location = lm.getLastKnownLocation(towers);

		if (location != null) {
			lat = (int) (location.getLatitude());
			longitu = (int) (location.getLongitude());
			latitudeEt.setText(String.valueOf(location.getLatitude()));
			longitudeEt.setText(String.valueOf(location.getLongitude()));
		} else {
			Toast.makeText(LoginActivity.this, "Couldn't get the provider",
					Toast.LENGTH_SHORT).show();
		}

		mProgress.setMessage("Loading data ...");

		if (mFsqApp.hasAccessToken())
		{
			//nameTv.setText("Connected as " + mFsqApp.getUserName());			
//			FsqUser getUser = mFsqApp.fetchUser();
			//			
//			Toast.makeText(LoginActivity.this, getUser.firstName + " " + getUser.id + " " + getUser.homeCity,  Toast.LENGTH_LONG).show();
			
			startActivity(new Intent(LoginActivity.this, MainActivity.class).putExtra("username", mFsqApp.getUserName()));
			finish();
		}

		FsqAuthListener listener = new FsqAuthListener() {
			@Override
			public void onSuccess() {
				Toast.makeText(LoginActivity.this,
						"Connected as " + mFsqApp.getUserName(),
						Toast.LENGTH_SHORT).show();
				nameTv.setText("Connected as " + mFsqApp.getUserName());
				startActivity(new Intent(LoginActivity.this, MainActivity.class).putExtra("username", mFsqApp.getUserName()));
//				FsqUser getUser = mFsqApp.fetchUser();				
//				Toast.makeText(LoginActivity.this, getUser.firstName + " " + getUser.id + " " + getUser.homeCity,  Toast.LENGTH_LONG).show();
				finish();
			}

			@Override
			public void onFail(String error) {
				Toast.makeText(LoginActivity.this, error, Toast.LENGTH_SHORT)
						.show();
			}
		};

		mFsqApp.setListener(listener);

		// get access token and user name from foursquare
		connectBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mFsqApp.authorize();
			}
		});

		// use access token to get nearby places
		goBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String latitude = latitudeEt.getText().toString();
				String longitude = longitudeEt.getText().toString();

				if (latitude.equals("") || longitude.equals("")) {
					Toast.makeText(LoginActivity.this,
							"Latitude or longitude is empty",
							Toast.LENGTH_SHORT).show();
					return;
				}

				double lat = Double.valueOf(latitude);
				double lon = Double.valueOf(longitude);

				loadNearbyPlaces(lat, lon);
			}
		});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	private void loadNearbyPlaces(final double latitude, final double longitude) {
		mProgress.show();

		new Thread() {
			@Override
			public void run() {
				int what = 0;

				try {

					mNearbyList = mFsqApp.getNearby(latitude, longitude);
				} catch (Exception e) {
					what = 1;
					e.printStackTrace();
				}

				mHandler.sendMessage(mHandler.obtainMessage(what));
			}
		}.start();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();

			if (msg.what == 0) {
				if (mNearbyList.size() == 0) {
					Toast.makeText(LoginActivity.this,
							"No nearby places available", Toast.LENGTH_SHORT)
							.show();
					return;
				}

				mAdapter.setData(mNearbyList);
				mListView.setAdapter(mAdapter);
			} else {
				Toast.makeText(LoginActivity.this,
						"Failed to load nearby places", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onLocationChanged(Location l) {
		// TODO Auto-generated method stub

		lat = (int) (l.getLatitude());
		longitu = (int) (l.getLongitude());
		latitudeEt.setText(String.valueOf(l.getLatitude()));
		longitudeEt.setText(String.valueOf(l.getLongitude()));

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		lm.removeUpdates(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		lm.requestLocationUpdates(towers, 500, 1, this);
	}
}
